//
//  ChatViewController.m
//  HAZDoctor
//
//  Created by 李晓俊 on 2018/10/23.
//  Copyright © 2018年 李晓俊. All rights reserved.
//

#import "ChatViewController.h"
#import "EaseMedicineCell.h"
#import "GYWebviewctl.h"
#import "MTFeedBackVC.h"
//#import "ChatJubaoVC.h"
@interface ChatViewController ()<EaseChatBarMoreViewDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
@property(nonatomic ,strong) UIAlertController *alert;
@property(nonatomic ,strong) UIAlertController *alert2;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    [[EaseMedicineCell appearance]setAvatarSize:40.0f];
    [[EaseMedicineCell appearance]setAvatarCornerRadius:20.0f];

    [[EaseChatBarMoreView appearance] setMoreViewBackgroundColor:KWhiteColor];
    [self.chatBarMoreView removeItematIndex:4];
    [self.chatBarMoreView removeItematIndex:3];
    [self.chatBarMoreView removeItematIndex:1];
    self.chatBarMoreView.delegate = self;
//    [self.chatBarMoreView insertItemWithImage:[UIImage imageNamed:@"聊天表情"] highlightedImage:[UIImage imageNamed:@"聊天表情"] title:@"表情包"];
    [self.chatBarMoreView setHeight:90];
    self.view.backgroundColor = KWhiteColor;
    self.tableView.backgroundColor = KWhiteColor;
    
    [self CreateNav];
    [self setNav];
}
- (void) setNav {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"jubao"] style:UIBarButtonItemStyleDone target:self action:@selector(rightClick)];
    self.navigationItem.rightBarButtonItem = rightBtn;
}
//举报
- (void)rightClick {
    [self.view endEditing:YES];
    if (!self.alert) {
        self.alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"拉黑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self lahei];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //意见
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
    }
    [self presentViewController:self.alert animated:true completion:nil];
   
}
-(void)CreateNav
{
    //默认返回事件
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc ]initWithImage:[UIImage imageWithOriginalName:@"返回黑色"] style:UIBarButtonItemStyleDone target:self action:@selector(returnAction)];
    self.navigationItem.leftBarButtonItem = leftBtn;
}
- (void)returnAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
                            modelForMessage:(EMMessage *)message
{
    id<IMessageModel> model = [[EaseMessageModel alloc] initWithMessage:message];
    Message *msg = [Message getOneObjectByUserID:message.from];

    if (model.isSender) {
        //自己发送
        model.nickname = KUSER.nickName;
        model.avatarURLPath = KUSER.portraitMap;
    }else {
//        self.doctorUser = [message.ext objectForKey:@"doctorUser"];
        //别人发送
        if (msg.username) {
            model.nickname = msg.username;
        }
        if (msg.headImageUrl) {
            model.avatarURLPath = msg.headImageUrl;
        }
    }
    
    model.avatarImage = [UIImage imageNamed:@"EaseUIResource.bundle/user"];
    model.failImageName = @"imageDownloadFail";
    
    return model;
}
- (void)messageViewController:(EaseMessageViewController *)viewController
            didSelectMoreView:(EaseChatBarMoreView *)moreView
                      AtIndex:(NSInteger)index {
    if (index == 2) {
        [self imgClick];
        
        //自定义按钮
    }else {
        
    }
 }


-  (void)imgClick {
    //发送产品信息
    NSDictionary *dict = @{@"records":@"1",
                               @"send_username":KUSER.nickName,
                           @"username":KUSER.nickName,
                           @"recever_username":self.username,
                           @"headImageUrl":KUSER.portraitMap,
                           @"send_details":@""
                           };
    EMTextMessageBody *msgB = [[EMTextMessageBody alloc] initWithText:@"通过考验"];
    NSString *from = [[EMClient sharedClient] currentUsername];
    NSString *to = self.conversation.conversationId;
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:msgB ext:dict];
    message.chatType = EMChatTypeChat; // 消息类型
    message.ext = dict;
    __weak typeof(self) weakSelf = self;
    // 发送消息 （调用 EaseMessageViewController 中的方法）
    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
    } completion:^(EMMessage *message, EMError *error) {
        if (!error) {
            [weakSelf addMessageToDataSource:message progress:nil];
            [weakSelf.tableView reloadData];
        }
    }];
    
}

- (UITableViewCell *)messageViewController:(UITableView *)tableView cellForMessageModel:(id<IMessageModel>)messageModel {
    NSDictionary *ext = messageModel.message.ext;
    if (messageModel.bodyType == EMMessageBodyTypeText  && [[NSString stringWithFormat:@"%@",[ext objectForKey:@"records"]] isEqualToString:@"1"]) {
        NSString *cellid = [EaseMedicineCell cellIdentifierWithModel:messageModel];
        EaseMedicineCell *medicneCell = (EaseMedicineCell *)[tableView dequeueReusableCellWithIdentifier:cellid];
        if (!medicneCell) {
            medicneCell = [[EaseMedicineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid model:messageModel];
        }
        medicneCell.backgroundColor = [UIColor clearColor];
        medicneCell.model = messageModel;
        if (messageModel.isSender) {
            //自己发送
            medicneCell.tishiLabel.text = [NSString stringWithFormat:@"你通过了%@创建的卡牌",[ext objectForKey:@"recever_username"]];
        }else {
            medicneCell.tishiLabel.text = [NSString stringWithFormat:@"%@通过了你创建的卡牌",[ext objectForKey:@"send_username"]];
        }
        return medicneCell;
    }
    return nil;
}
- (CGFloat)messageViewController:(EaseMessageViewController *)viewController heightForMessageModel:(id<IMessageModel>)messageModel withCellWidth:(CGFloat)cellWidth {
    NSDictionary *ext = messageModel.message.ext;
    if (ext) {
        if (messageModel.bodyType == EMMessageBodyTypeText  && [[NSString stringWithFormat:@"%@",[ext objectForKey:@"records"]] isEqualToString:@"1"]) {
            return [EaseMedicineCell cellHeightWithModel:messageModel];
        }
    }
    return 0;
}
//点击了自定义的cell
- (void)didSelectMessageModel:(id<IMessageModel>)messageModel {
    DLog(@"自定义的cell点击了");
 }


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置导航栏默认的背景颜色
 
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (void)lahei {
    if (!self.alert2) {
        self.alert2 = [UIAlertController alertControllerWithTitle:@"确定拉黑该用户吗？拉黑对方后不能对你发送消息" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [self.alert2 addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (self.userid.length > 0) {
                AccountService *acc = [AccountService getObject];
                acc.httpRequestResultBlock = ^(id data,int code){

                };
                [acc blacklistAdd:self.userid];
            }
            EMError *error = [[EMClient sharedClient].contactManager addUserToBlackList:self.conversation.conversationId relationshipBoth:YES];
            if (!error) {
                
            }
            // 删除好友
            EMError *error2 = [[EMClient sharedClient].contactManager deleteContact:self.conversation.conversationId isDeleteConversation:YES];
            if (!error2) {
                [self.view makeToast:@"拉黑成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            }
        }]];
        [self.alert2 addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
    }
    [self presentViewController:self.alert2 animated:true completion:nil];
}
@end
